package com.example.petshopping.ui.orders;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.petshopping.ui.orders.adapter.SimpleOrderAdapter;
import com.example.petshopping.ui.orders.model.Order;
import com.example.petshopping.model.AppCartListResponseVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.network.RetrofitClient;
import com.google.android.material.tabs.TabLayout;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.ArrayList;
import java.util.List;

public class OrdersActivity extends AppCompatActivity {

    private static final String TAG = "OrdersActivity";
    
    // UI 组件
    private RecyclerView recyclerView;
    private View layoutEmpty;
    private TabLayout tabLayout;
    
    // 数据
    private List<Order> orderList = new ArrayList<>();
    private List<Order> originalOrderList = new ArrayList<>(); // 保存原始数据
    private SimpleOrderAdapter adapter;
    private boolean isLoadingData = false; // 加载状态标志

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_orders);
            
            initViews(); // 初始化UI组件
            setupListeners(); // 设置事件监听器
            loadDemoData(); // 加载演示数据
            setupRecyclerView(); // 设置RecyclerView
            
            // 处理传入的标签参数
            handleTabIntent();
            
        } catch (Exception e) {
            Log.e(TAG, "初始化错误: " + e.getMessage(), e);
            Toast.makeText(this, "页面加载失败，请稍后再试", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    
    private void initViews() {
        recyclerView = findViewById(R.id.rv_orders);
        layoutEmpty = findViewById(R.id.layout_empty);
        tabLayout = findViewById(R.id.tab_layout);
        
        // 设置返回按钮
        View btnBack = findViewById(R.id.btn_back);
        if (btnBack != null) {
            btnBack.setOnClickListener(v -> finish());
        }
        
        // 阻止搜索框自动聚焦
        View etSearch = findViewById(R.id.et_search);
        if (etSearch != null) {
            etSearch.clearFocus();
        }
    }
    
    private void setupListeners() {
        // Tab切换监听
        if (tabLayout != null) {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                    filterOrdersByTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });
    }
    }
    
    private void handleTabIntent() {
        try {
            Intent intent = getIntent();
            if (intent != null && intent.hasExtra("default_tab")) {
                int tabIndex = intent.getIntExtra("default_tab", 0);
                
                // 确保索引有效
                if (tabLayout != null && tabIndex >= 0 && tabIndex < tabLayout.getTabCount()) {
                    TabLayout.Tab tab = tabLayout.getTabAt(tabIndex);
                    if (tab != null) {
                        tab.select();
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "处理标签参数错误: " + e.getMessage(), e);
        }
    }
    
    private void setupRecyclerView() {
        if (recyclerView == null) return;
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SimpleOrderAdapter(this, orderList);
        recyclerView.setAdapter(adapter);
        
        updateEmptyView();
    }
    
    private void loadDemoData() {
        // 首先尝试加载真实数据
        loadCartDisplayData();
        
        // 创建演示数据作为备选
        loadDemoOrderData();
    }
    
    /**
     * 加载待确认商品的真实数据
     * 对接后端 /trade/cart/display/list 接口获取用户的待确认商品列表
     * 支持普通商品SPU和拍卖商品两种类型
     * 网络请求失败时会自动降级使用演示数据
     */
    private void loadCartDisplayData() {
        if (isLoadingData) {
            Log.d(TAG, "正在加载数据，跳过重复请求");
            return;
        }
        
        isLoadingData = true;
        Call<CommonResult<AppCartListResponseVO>> call = RetrofitClient.getInstance()
                .getApiService()
                .getCartDisplayList();
        
        call.enqueue(new Callback<CommonResult<AppCartListResponseVO>>() {
            @Override
            public void onResponse(Call<CommonResult<AppCartListResponseVO>> call, 
                                 Response<CommonResult<AppCartListResponseVO>> response) {
                isLoadingData = false;
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        CommonResult<AppCartListResponseVO> result = response.body();
                        if (result.isSuccess() && result.getData() != null) {
                            // 转换数据并更新UI
                            convertCartDataToOrders(result.getData());
                            Log.i(TAG, "成功加载待确认商品列表数据");
                            return;
                        } else {
                            Log.w(TAG, "API返回失败: " + result.getMsg());
                        }
                    } else {
                        Log.w(TAG, "响应不成功: " + response.code());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理待确认商品列表响应时出错: " + e.getMessage(), e);
                }
                // 如果网络请求失败，使用演示数据
                Log.i(TAG, "使用演示数据作为备选");
            }

            @Override
            public void onFailure(Call<CommonResult<AppCartListResponseVO>> call, Throwable t) {
                isLoadingData = false;
                Log.w(TAG, "网络请求失败，使用演示数据: " + t.getMessage());
                // 网络请求失败时，保持使用演示数据，不显示错误提示
            }
        });
    }
    
    /**
     * 将购物车数据转换为订单数据
     */
    private void convertCartDataToOrders(AppCartListResponseVO cartData) {
        List<Order> realOrders = new ArrayList<>();
        
        // 处理有效的购物车项目
        if (cartData.getValidList() != null) {
            for (AppCartListResponseVO.Cart cart : cartData.getValidList()) {
                Order order = convertCartToOrder(cart, false);
                if (order != null) {
                    realOrders.add(order);
                }
            }
        }
        
        // 处理无效的购物车项目
        if (cartData.getInvalidList() != null) {
            for (AppCartListResponseVO.Cart cart : cartData.getInvalidList()) {
                Order order = convertCartToOrder(cart, true);
                if (order != null) {
                    realOrders.add(order);
                }
            }
        }
        
        // 如果有真实数据，则替换演示数据
        if (!realOrders.isEmpty()) {
            // 保存原始数据
            originalOrderList.clear();
            originalOrderList.addAll(realOrders);
            
            orderList.clear();
            orderList.addAll(realOrders);
            
            // 更新UI
            runOnUiThread(() -> {
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                updateEmptyView();
                // 如果当前选中的是待确认tab，重新过滤数据
                if (tabLayout != null) {
                    TabLayout.Tab selectedTab = tabLayout.getTabAt(tabLayout.getSelectedTabPosition());
                    if (selectedTab != null) {
                        filterOrdersByTab(selectedTab.getPosition());
                    }
                }
            });
        } else {
            Log.i(TAG, "没有获取到真实的待确认商品数据，继续使用演示数据");
        }
    }
    
    /**
     * 将单个购物车项目转换为订单
     */
    private Order convertCartToOrder(AppCartListResponseVO.Cart cart, boolean isInvalid) {
        if (cart == null) return null;
        
        Order order = new Order();
        order.setId(cart.getId() != null ? cart.getId().toString() : "unknown");
        order.setStatus(Order.STATUS_PENDING_CONFIRM);
        order.setQuantity(cart.getCount() != null ? cart.getCount() : 1);
        order.setAuctionItemId(cart.getAuctionItem().getId() != null ? cart.getAuctionItem().getId().toString() : "unknown");
        // 处理SPU商品信息
        if (cart.getSpu() != null) { 
            order.setProductTitle(cart.getSpu().getName() != null ? 
                cart.getSpu().getName() : "商品名称");
            
            // 设置商品图片 - 优先使用API返回的图片URL
            if (!TextUtils.isEmpty(cart.getSpu().getPicUrl())) {
                order.setProductImageUrl(cart.getSpu().getPicUrl());
            } else {
                order.setProductImageResId(R.drawable.dog); // 默认商品图片
            }
        }
        
        // 处理拍卖商品信息
        if (cart.getAuctionItem() != null) {
            order.setStoreName(cart.getAuctionItem().getSellerName() != null ? 
                cart.getAuctionItem().getSellerName() : "拍卖卖家");
            
            // 设置卖家头像 - 优先使用API返回的头像URL
            if (!TextUtils.isEmpty(cart.getAuctionItem().getSellerAvatar())) {
                order.setStoreAvatarUrl(cart.getAuctionItem().getSellerAvatar());
            } else {
                order.setStoreAvatarResId(R.drawable.yugang); // 默认头像资源ID
            }
            
            // 使用拍卖当前价格
            Integer currentPrice = cart.getAuctionItem().getCurrentPrice();
            if (currentPrice != null) {
                String priceStr = "¥ " + currentPrice.toString();
                String totalPrice = String.valueOf(currentPrice * cart.getCount());
                order.setPrice(priceStr); // 设置当前价格
                order.setTotalAmount("实付：¥ " + totalPrice); // 设置总金额(实际价格)
            } else {
                order.setPrice("异常");
                order.setTotalAmount("异常");
            }
        }
        
        return order;
    }
    
    private void loadDemoOrderData() {
        // 原有的演示数据创建逻辑
        orderList.clear();
        // ---------------------------
        // 待付款订单
        Order order1 = new Order();
        order1.setId("20230501001");
        order1.setStoreName("宠物之家");
        order1.setStoreAvatarResId(R.drawable.dog); // 设置店铺头像
        order1.setStatus(Order.STATUS_PENDING_PAYMENT);
        order1.setProductTitle("宠物食品狗粮天然粮泰迪金毛拉布拉多成犬幼犬通用型");
        order1.setProductImageResId(R.drawable.cat);
        order1.setPrice("¥128.00");
        order1.setQuantity(1);
        order1.setTotalAmount("¥128.00");
        orderList.add(order1);
        
        // 待发货订单
        Order order2 = new Order();
        order2.setId("20230501002");
        order2.setStoreName("宠物用品专营");
        order2.setStoreAvatarResId(R.drawable.cat); // 设置店铺头像
        order2.setStatus(Order.STATUS_PENDING_SHIPMENT);
        order2.setProductTitle("宠物玩具球狗狗耐咬磨牙发声玩具");
        order2.setProductImageResId(R.drawable.dog);
        order2.setPrice("¥39.90");
        order2.setQuantity(2);
        order2.setTotalAmount("¥79.80");
        orderList.add(order2);
        
        // 待收货订单
        Order order3 = new Order();
        order3.setId("20230501003");
        order3.setStoreName("鱼缸专卖");
        order3.setStoreAvatarResId(R.drawable.yugang); // 设置店铺头像
        order3.setStatus(Order.STATUS_PENDING_RECEIPT);
        order3.setProductTitle("小型生态鱼缸水族箱玻璃创意桌面金鱼缸");
        order3.setProductImageResId(R.drawable.yugang);
        order3.setPrice("¥299.00");
        order3.setQuantity(1);
        order3.setTotalAmount("¥299.00");
        orderList.add(order3);
        
        // 待确认订单
        Order order4 = new Order();
        order4.setId("20230501004");
        order4.setStoreName("宜物生活馆");
        order4.setStoreAvatarResId(R.drawable.cat); // 设置店铺头像
        order4.setStatus(Order.STATUS_PENDING_CONFIRM);
        order4.setProductTitle("宜物猫砂除臭抗菌猫厨用品吸水速干");
        order4.setProductImageResId(R.drawable.cat);
        order4.setPrice("¥49.90");
        order4.setQuantity(2);
        order4.setTotalAmount("¥99.80");
        orderList.add(order4);
        
        // 已完成订单
        Order order5 = new Order();
        order5.setId("20230501005");
        order5.setStoreName("鸟食专卖");
        order5.setStoreAvatarResId(R.drawable.yingwu); // 设置店铺头像
        order5.setStatus(Order.STATUS_COMPLETED);
        order5.setProductTitle("鹦鹉饲料鸟粮混合谷物鸟食");
        order5.setProductImageResId(R.drawable.yingwu);
        order5.setPrice("¥68.00");
        order5.setQuantity(3);
        order5.setTotalAmount("¥204.00");
        orderList.add(order5);
    }
    
    private void filterOrdersByTab(int tabPosition) {
        if (adapter == null) return;
        
        List<Order> filteredList = new ArrayList<>();
        
        switch (tabPosition) {
            case 0: // 全部
                filteredList.addAll(orderList);
                break;
            case 1: // 待确认 - 重新加载数据确保最新
                if (!isLoadingData) {
                    // 当切换到待确认tab时，尝试重新获取最新数据
                    loadCartDisplayData();
                }
                for (Order order : orderList) {
                    if (order.getStatus() == Order.STATUS_PENDING_CONFIRM) {
                        filteredList.add(order);
                    }
                }
                break;
            case 2: // 待付款
                for (Order order : orderList) {
                    if (order.getStatus() == Order.STATUS_PENDING_PAYMENT) {
                        filteredList.add(order);
                    }
                }
                break;
            case 3: // 待发货
                for (Order order : orderList) {
                    if (order.getStatus() == Order.STATUS_PENDING_SHIPMENT) {
                        filteredList.add(order);
                    }
                }
                break;
            case 4: // 待收货
                for (Order order : orderList) {
                    if (order.getStatus() == Order.STATUS_PENDING_RECEIPT) {
                        filteredList.add(order);
                    }
                }
                break;
            case 5: // 退款/售后
                for (Order order : orderList) {
                    if (order.getStatus() == Order.STATUS_REFUND) {
                        filteredList.add(order);
                    }
                }
                break;
        }
        
        adapter.updateData(filteredList);
        updateEmptyView();
        
        // 记录过滤结果
        Log.d(TAG, "过滤结果: tab=" + tabPosition + ", 显示" + filteredList.size() + "条订单");
    }
    
    private void updateEmptyView() {
        if (recyclerView == null || layoutEmpty == null || adapter == null) return;
        
        if (adapter.getItemCount() == 0) {
            recyclerView.setVisibility(View.GONE);
            layoutEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            layoutEmpty.setVisibility(View.GONE);
        }
    }
    
    /**
     * 获取待确认订单数量
     */
    public int getPendingConfirmOrderCount() {
        int count = 0;
        for (Order order : orderList) {
            if (order.getStatus() == Order.STATUS_PENDING_CONFIRM) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 刷新待确认商品列表数据（公开方法，供外部调用）
     */
    public void refreshPendingConfirmOrders() {
        Log.i(TAG, "手动刷新待确认商品列表");
        loadCartDisplayData();
    }
    
    /**
     * 获取当前是否正在加载数据
     */
    public boolean isLoadingData() {
        return isLoadingData;
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 页面恢复时，如果当前显示的是待确认tab，则刷新数据
        if (tabLayout != null && tabLayout.getSelectedTabPosition() == 1) {
            Log.d(TAG, "页面恢复，刷新待确认商品数据");
            loadCartDisplayData();
        }
    }
} 